package api

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/swaggo/files"
	"github.com/swaggo/gin-swagger"
	"blockchain-api/internal/config"
	"blockchain-api/internal/middleware"
	"blockchain-api/internal/services"
	"blockchain-api/pkg/logger"
)

// Server API服务器
type Server struct {
	config   *config.Config
	services *services.Services
	router   *gin.Engine
}

// NewServer 创建新的API服务器
func NewServer(cfg *config.Config, svc *services.Services) *gin.Engine {
	server := &Server{
		config:   cfg,
		services: svc,
	}

	// 设置Gin模式
	if cfg.Server.Host == "0.0.0.0" {
		gin.SetMode(gin.ReleaseMode)
	}

	// 创建路由器
	server.router = gin.New()

	// 添加中间件
	server.router.Use(middleware.Logger())
	server.router.Use(middleware.Recovery())
	server.router.Use(middleware.CORS())

	// 设置路由
	server.setupRoutes()

	return server.router
}

// setupRoutes 设置API路由
func (s *Server) setupRoutes() {
	// 健康检查
	s.router.GET("/health", s.healthCheck)
	s.router.GET("/ping", s.ping)

	// API文档
	s.router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// API v1 路由组
	v1 := s.router.Group("/api/v1")
	{
		// 钱包相关API
		wallets := v1.Group("/wallets")
		{
			wallets.POST("", s.createWallet)
			wallets.GET("", s.listWallets)
			wallets.GET("/:name", s.getWallet)
			wallets.DELETE("/:name", s.deleteWallet)
			wallets.GET("/:name/balance", s.getWalletBalance)
		}

		// 区块链相关API
		blockchain := v1.Group("/blockchain")
		{
			blockchain.GET("/info", s.getBlockchainInfo)
			blockchain.GET("/validate", s.validateBlockchain)
			blockchain.GET("/blocks", s.getBlocks)
			blockchain.GET("/blocks/:index", s.getBlock)
			blockchain.POST("/mine", s.mineBlock)
		}

		// 交易相关API
		transactions := v1.Group("/transactions")
		{
			transactions.POST("", s.createTransaction)
			transactions.GET("", s.getTransactions)
			transactions.GET("/:hash", s.getTransaction)
		}

		// 地址相关API
		addresses := v1.Group("/addresses")
		{
			addresses.GET("/:address/balance", s.getAddressBalance)
			addresses.GET("/:address/transactions", s.getAddressTransactions)
		}
	}
}

// healthCheck 健康检查
func (s *Server) healthCheck(c *gin.Context) {
	// 检查数据库连接
	if err := s.services.HealthCheck(); err != nil {
		logger.Error("Health check failed:", err)
		c.JSON(http.StatusServiceUnavailable, gin.H{
			"status": "unhealthy",
			"error":  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":    "healthy",
		"timestamp": time.Now().Unix(),
		"version":   "1.0.0",
	})
}

// ping 简单ping检查
func (s *Server) ping(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "pong",
		"time":    time.Now().Format(time.RFC3339),
	})
}